package com.darryring.fast.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.darryring.fast.R;
import com.darryring.fast.adapter.ImagePagerAdapter;
import com.darryring.libview.PagerTitleSpotTabStrip;
import com.darryring.libview.app.CameraActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hljdrl on 16/3/2.
 */
public class FirstFragment extends BaseFragment implements ViewPager.OnPageChangeListener,AdapterView.OnItemClickListener{


    ListView mListview;
    ListAdapter mListAdapter;
    ViewPager mViewPager;
    PagerTitleSpotTabStrip mPagerTitleSpotTabStrip;
    ImagePagerAdapter mImagePagerAdapter;
    List<String> imageUrls = new ArrayList<String>();
    List<View> imageViews = new ArrayList<View>();
    public FirstFragment(){
    }
    @SuppressLint("ValidFragment")
    public FirstFragment(String _title){
        setTitle(_title);
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View _view = inflater.inflate(R.layout.fragment_first,container,false);
        return _view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        View _view = getView();
        mListview = (ListView) _view.findViewById(R.id.listview_first);
        //==================================================================
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View headerView = inflater.inflate(R.layout.content_session_header,mListview,false);
        mListview.addHeaderView(headerView);
        //==================================================================
        mViewPager = (ViewPager) headerView.findViewById(R.id.image_viewpager);
        mPagerTitleSpotTabStrip = (PagerTitleSpotTabStrip) headerView.findViewById(R.id.pager_spot_strip);
        //==================================================================
        mListAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_expandable_list_item_1,getData());
        mListview.setAdapter(mListAdapter);
        //==================================================================
        imageUrls.add("http://img.zcool.cn/community/01d4d756e6c00232f875520fa3f04f.jpg@900w_1l_2o");
        imageUrls.add("http://img.zcool.cn/community/0197df569c435c32f87574be0acb1a.jpg@900w_1l_2o");
        imageUrls.add("http://img.zcool.cn/community/01d7be569c436032f87574be192fba.jpg@900w_1l_2o");
        imageUrls.add("http://img.zcool.cn/community/01a18e569c43676ac725af23f4066f.jpg@900w_1l_2o");

        imageUrls.add("http://img.zcool.cn/community/012876569c436e6ac725af233f88e3.jpg@900w_1l_2o");

        imageUrls.add("http://img.zcool.cn/community/019f70569c436f32f87574be5bdc2d.jpg@900w_1l_2o");
        imageUrls.add("http://img.zcool.cn/community/0169b9569c437b6ac725af23af5002.jpg@900w_1l_2o");
        imageUrls.add("http://img.zcool.cn/community/01bcde569c438d32f87574be94ef23.jpg@900w_1l_2o");
        imageUrls.add("http://img.zcool.cn/community/017cfe569c437c32f87574be3a3efd.jpg@900w_1l_2o");
        imageUrls.add("http://img.zcool.cn/community/0177c7569c43896ac725af237b3ab1.jpg@900w_1l_2o");
        imageViews.addAll(getImageViews());
        mImagePagerAdapter = new ImagePagerAdapter(imageViews,imageUrls);
        mViewPager.setAdapter(mImagePagerAdapter);
        mPagerTitleSpotTabStrip.setTabTextBackground(R.drawable.pager_spot_selector);
        mPagerTitleSpotTabStrip.setViewPager(mViewPager);

        mHandler.removeMessages(HANDLER_VIEWPAGER_NEXT);
        mViewPager.addOnPageChangeListener(this);
        mHandler.sendEmptyMessageDelayed(HANDLER_VIEWPAGER_NEXT,mPagerDelayed);
        mListview.setOnItemClickListener(this);
    }
    private List<View> getImageViews()
    {
        List<View> _views = new ArrayList<View>();
        LayoutInflater inflater = LayoutInflater.from(getContext());
        for(int i=0;i<10;i++) {
            View _newView = inflater.inflate(R.layout.item_image_pager,null);
            _views.add(_newView);
        }
        return _views;
    }
    private List<String> getData(){

        List<String> data = new ArrayList<String>();
        String[] raWdata = getResources().getStringArray(R.array.session_array);
        for(int i=0;i<raWdata.length;i++) {
            data.add(raWdata[i]);
        }
        return data;
    }

    @Override
    public void onResume() {
        super.onResume();
        mHandler.removeMessages(HANDLER_VIEWPAGER_NEXT);
        mHandler.sendEmptyMessageDelayed(HANDLER_VIEWPAGER_NEXT,mPagerDelayed);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mViewPager!=null){
            mViewPager.removeOnPageChangeListener(this);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        mHandler.removeMessages(HANDLER_VIEWPAGER_NEXT);
    }

    //=========================================================================================
    //=========================================================================================
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        mHandler.removeMessages(HANDLER_VIEWPAGER_NEXT);
        mHandler.sendEmptyMessageDelayed(HANDLER_VIEWPAGER_NEXT,mPagerDelayed);
    }

    @Override
    public void onPageSelected(int position) {
        mHandler.removeMessages(HANDLER_VIEWPAGER_NEXT);
        mHandler.sendEmptyMessageDelayed(HANDLER_VIEWPAGER_NEXT,mPagerDelayed);

    }
    @Override
    public void onPageScrollStateChanged(int state) {


    }
    //=========================================================================================
    //=========================================================================================
    private int mPagerDelayed = 3000;
    private final int HANDLER_VIEWPAGER_NEXT=10;
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what){
                case HANDLER_VIEWPAGER_NEXT:
                    if(mViewPager!=null&&mImagePagerAdapter!=null){
                        int _curItem = mViewPager.getCurrentItem();
                        if(_curItem<(mImagePagerAdapter.getCount()-1)){
                            mViewPager.setCurrentItem(_curItem+1);
                        }else{
                            mViewPager.setCurrentItem(0,false);
                        }
                        sendEmptyMessageDelayed(msg.what,mPagerDelayed);
                    }
                    break;
            }
        }
    };
    //======================================================================================
    private static final int REQUEST_CAMERA = 0;
    final int REQUEST_CAMERA_PERMISSION = 0;
    // Check for camera permission in MashMallow
    public void requestForCameraPermission() {
        final String permission = Manifest.permission.CAMERA;
        if (ContextCompat.checkSelfPermission(getActivity(), permission)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), permission)) {
                // Show permission rationale
            } else {
                // Handle the result in Activity#onRequestPermissionResult(int, String[], int[])
                ActivityCompat.requestPermissions(getActivity(), new String[]{permission}, REQUEST_CAMERA_PERMISSION);
            }
        } else {
            // Start CameraActivity
            Intent startCustomCameraIntent = new Intent(getActivity(), CameraActivity.class);
            startActivityForResult(startCustomCameraIntent, REQUEST_CAMERA);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(requestCode==REQUEST_CAMERA_PERMISSION){
            // Start CameraActivity
            Intent startCustomCameraIntent = new Intent(getActivity(), CameraActivity.class);
            startActivityForResult(startCustomCameraIntent, REQUEST_CAMERA);
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) return;

        if (requestCode == REQUEST_CAMERA) {
            Uri photoUri = data.getData();
        }
        super.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            String _select = (String) adapterView.getAdapter().getItem(i);
            if(_select.equals(mListAdapter.getItem(0))){
                requestForCameraPermission();
            }
    }
}
